package service

import (
	"context"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"webook/internal/domain"
	"webook/internal/repository"
	"webook/internal/repository/dao"
)

var (
	ErrUserDuplicateEmail = dao.ErrUserDuplicateEmail
	ErrUserNotFound       = dao.ErrUserNotFound
)

type UserService struct {
	dao *repository.UserRepository
}

func NewUserService(dao *repository.UserRepository) *UserService {
	return &UserService{
		dao: dao,
	}
}

func (svc *UserService) SignUp(ctx context.Context, u domain.User) error {
	hash, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	u.Password = string(hash)
	return svc.dao.CreateUser(ctx, u)
}

func (svc *UserService) Login(c *gin.Context, user domain.User) (domain.User, error) {
	u, err := svc.dao.FindByEmail(c, user.Email)
	if err != nil {
		return domain.User{}, ErrUserNotFound
	}
	err = bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(user.Password))
	return u, err
}

func (svc *UserService) GetUserProfile(ctx context.Context, id int64) (domain.User, error) {
	user, err := svc.dao.GetUserProfileById(ctx, id)
	if err != nil {
		return domain.User{}, err
	}
	return user, nil
}

func (svc *UserService) Edit(c *gin.Context, user domain.User) error {
	err := svc.dao.UpdateUser(c, user)
	return err
}
